package com.jwaoo.mobile.view.main;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Canvas;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CheckedTextView;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.Toast;
import com.dx.as.LoadingDialog;
import com.dx.as.ToastUtil;
import com.dx.as.ToolBarOptions;
import com.dx.as.UI;
import com.dx.as.common.CommonUtils;
import com.dx.as.common.FragmentUtils;
import com.dx.as.common.log.LogUtil;
import com.dx.as.permission.MPermission;
import com.dx.as.permission.annotation.OnMPermissionDenied;
import com.dx.as.permission.annotation.OnMPermissionGranted;
import com.dx.as.permission.annotation.OnMPermissionNeverAskAgain;
import com.dx.cardswipe.SwipeFlingAdapterView;
import com.dx.sliding.SlidingMenu;
import com.jwaoo.chat.fragment.session.SessionActivity;
import com.jwaoo.mobile.R;
import com.jwaoo.mobile.forchat.IFroChatMouleImpl;
import com.jwaoo.mobile.view.account.MeFragment;
import com.jwaoo.mobile.view.explore.UserFragment;
import com.jwaoo.mobile.view.explore.adapter.UserRecyclerViewAdapter;
import com.jwaoo.mobile.view.explore.bean.UserBean;
import com.jwaoo.mobile.view.explore.presenter.IUserView;
import com.jwaoo.mobile.view.explore.presenter.UserPresenter;
import com.jwaoo.mobile.view.hot.HotFragment;
import com.jwaoo.mobile.view.like.LikeActivity;
import com.jwaoo.mobile.view.login.LoginActivity;
import com.jwaoo.mobile.view.main.presenter.MainPresenter;
import com.nostra13.universalimageloader.core.ImageLoader;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

public class MainActivity extends UI implements SwipeFlingAdapterView.onFlingListener,
        SwipeFlingAdapterView.OnItemClickListener ,IUserView {

    private final int BASIC_PERMISSION_REQUEST_CODE = 100;
    private final int OVERLAY_PERMISSION_REQ_CODE = 1001;
    private MainPresenter mainPresenter;
    private View tv_sign;
    private long previousTime ;
    private static Activity activity;
    private RadioButton [] radioButtons;
    private SlidingMenu menu;
    private MenuView menuView;
    @Override
    protected void onActivityCreate(Bundle savedInstanceState) {
        setContentView(R.layout.activity_main);
        requestBasicPermission();
//        putDefaultFragment();
        presenter = new UserPresenter(this,this);
        setToolBar();
        activity = this;
        tv_sign = findView(R.id.tv_sign);
        mainPresenter = new MainPresenter(this);
        radioButtons = new RadioButton[]{findView(R.id.radio_hot),findView(R.id.radio_explore),findView(R.id.radio_message),findView(R.id.radio_me),};
        LoadingDialog.getInstance(getApplicationContext()).show();

        IFroChatMouleImpl.getInstance().setUnReadCountChangedListener(onUnReadChangeListener);
        initSliding();

        initView();
        loadData();
    }

    private void setToolBar(){
        ToolBarOptions toolBarOptions = new ToolBarOptions();
        toolBarOptions.leftDrawImgId = R.drawable.nav_sidebar_btn;
        toolBarOptions.rightDrawImgId = R.drawable.nav_chat_btn;
        toolBarOptions.showRightImg = true;
        toolBarOptions.showLeftImg = true;
        toolBarOptions.showRight = true;
        toolBarOptions.titleString = "SENSENOW";
        toolBarOptions.rightDrawId = R.drawable.nav_likes_btn;
        toolBarOptions.onLeftImgClickListener = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (menu.isMenuShowing()) menu.toggle();
                else menu.showMenu();
            }
        };
        toolBarOptions.onRightImgClickListener = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                goToNewActivity(SessionActivity.class);
            }
        };

        toolBarOptions.onRightClickListener = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                goToNewActivity(LikeActivity.class);
            }
        };

        setToolbar(toolBarOptions);
    }

    private void initSliding(){
        SlidingMenu.CanvasTransformer mtransformer = new SlidingMenu.CanvasTransformer(){
            @Override
            public void transformCanvas(Canvas canvas, float percentOpen) {
                float scale = (float) (percentOpen*0.25 + 0.75);
                canvas.scale(scale, scale, canvas.getWidth()/2, canvas.getHeight()/2);
            }
        };

        menu = new SlidingMenu(this);
        menu.setBehindCanvasTransformer(mtransformer);
        menu.setMode(SlidingMenu.LEFT);
        menu.setBehindScrollScale(0.3f);
//        menu.setTouchModeBehind(SlidingMenu.TOUCHMODE_MARGIN);
        menu.setTouchModeAbove(SlidingMenu.TOUCHMODE_NONE);
        menu.setShadowWidthRes(R.dimen.shadow_width);
//        menu.setShadowDrawable(com.dx.sliding.R.drawable.shadow);
        menu.setBehindOffsetRes(R.dimen.slidingmenu_offset);
        menu.setBehindWidth(getResources().getDimensionPixelSize(R.dimen.menu_w));
        menu.setFadeDegree(0.35f);
        menu.attachToActivity(this, SlidingMenu.SLIDING_CONTENT);
        //设置activity层内容UI移动效果
        //此方法为slidingmenu中自己增加的方法
        menu.setAboveCanvasTransformer(new SlidingMenu.CanvasTransformer() {

            @Override
            public void transformCanvas(Canvas canvas, float percentOpen) {
                float scale=1f-0.25f*percentOpen;
                canvas.scale(scale, scale,0,canvas.getHeight()/2);
            }
        });
        View view =  LayoutInflater.from(this).inflate(R.layout.menu, null);
        menu.setMenu(view);
        menuView = new MenuView(this,view,onLoginOut);
    }

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == OVERLAY_PERMISSION_REQ_CODE) {
            if (Build.VERSION.SDK_INT > 23){
                if (!Settings.canDrawOverlays(this)) {
                    Toast.makeText(this, "权限授予失败，无法开启悬浮窗", Toast.LENGTH_SHORT).show();
                    CommonUtils.setEnFloat(false);
                } else {
                    CommonUtils.setEnFloat(true);
                }
            }
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (menu != null && menu.isMenuShowing()) {
            menu.toggle();
        }
    }

    public void onViewClick(View view){

    }
    public static Activity getActivity(){
        return activity;
    }

    @Override
    protected void onResume() {
        super.onResume();
        mainPresenter.onResume();
        //启动Activity让用户授权
//        Log.d("fcm",CommonUtils.getPushToken());
    }

//    private void putDefaultFragment(){
////        HotFragment fragment = new HotFragment();
//        SessionFragment fragment = new SessionFragment();
//        FragmentUtils.putDefaultFragment(this,R.id.container,fragment);
//    }

    /**a
     * 基本权限管理
     */
    private final String[] BASIC_PERMISSIONS = new String[]{
            android.Manifest.permission.WRITE_EXTERNAL_STORAGE,
            android.Manifest.permission.READ_EXTERNAL_STORAGE,
            android.Manifest.permission.CAMERA,
            android.Manifest.permission.READ_PHONE_STATE,
            android.Manifest.permission.RECORD_AUDIO,
            android.Manifest.permission.ACCESS_COARSE_LOCATION,
            android.Manifest.permission.ACCESS_FINE_LOCATION
    };

    private void requestBasicPermission() {
        MPermission.printMPermissionResult(true, this, BASIC_PERMISSIONS);
        MPermission.with(MainActivity.this)
                .setRequestCode(BASIC_PERMISSION_REQUEST_CODE)
                .permissions(BASIC_PERMISSIONS)
                .request();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        MPermission.onRequestPermissionsResult(this, requestCode, permissions, grantResults);
    }

    @OnMPermissionGranted(BASIC_PERMISSION_REQUEST_CODE)
    public void onBasicPermissionSuccess() {
//        Toast.makeText(this, "授权成功", Toast.LENGTH_SHORT).show();
        MPermission.printMPermissionResult(false, this, BASIC_PERMISSIONS);
        requestFloatPermission();
    }

    @OnMPermissionDenied(BASIC_PERMISSION_REQUEST_CODE)
    @OnMPermissionNeverAskAgain(BASIC_PERMISSION_REQUEST_CODE)
    public void onBasicPermissionFailed() {
        Toast.makeText(this, "未全部授权，部分功能可能无法正常运行！", Toast.LENGTH_SHORT).show();
        MPermission.printMPermissionResult(false, this, BASIC_PERMISSIONS);
        requestFloatPermission();
    }

    private void requestFloatPermission(){
        try{
            if (Build.VERSION.SDK_INT > 23){
                if(!Settings.canDrawOverlays(getApplicationContext())) {
                    //启动Activity让用户授权
                    Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION, Uri.parse("package:" + getPackageName()));
                    startActivityForResult(intent,OVERLAY_PERMISSION_REQ_CODE);
                    return;
                }
            }
        }catch (Exception ex){
            LogUtil.d("MainActivity",ex.toString());
        }
    }

    @Override
    public void onBackPressed() {
        long current = System.currentTimeMillis();
        if (previousTime <= 0 || current - previousTime >= 1000){
            ToastUtil.showToast(this,"在按一次退出！");
            previousTime = current;
            return;
        }
        System.exit(0);
    }
    public void onMenuClick(View v){
        onMenuStateChange(v.getTag());
        switch (v.getId()){
            case R.id.radio_hot:
                FragmentUtils.goToFragment(MainActivity.this,HotFragment.class,R.id.container);
                break;
            case R.id.radio_explore:
                FragmentUtils.goToFragment(MainActivity.this,UserFragment.class,R.id.container);
                break;
            case R.id.radio_message:
//                FragmentUtils.goToFragment(MainActivity.this,SessionActivity.class,R.id.container);

                break;
            case R.id.radio_me:
                FragmentUtils.goToFragment(MainActivity.this,MeFragment.class,R.id.container);
                break;
        }
    }

    private void onMenuStateChange(Object tag){
        int index = Integer.parseInt(tag.toString()) - 1;
        for (int i = 0; i < radioButtons.length; i ++){
            radioButtons[i].setChecked(i == index);
        }
    }

    private int messageSum = 0;
    private IFroChatMouleImpl.OnUnReadChangeListener onUnReadChangeListener = new IFroChatMouleImpl.OnUnReadChangeListener() {
        @Override
        public void onUnReadCountChanged(final int count,final boolean isByDelete) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    int number = count;
                    if (isByDelete){
                        if (messageSum > 0){
                            try{
                                number = messageSum - count;
                            }catch (Exception ex){
                                LogUtil.e("MainActivity",ex.toString());
                            }
                        }
                    }
                    messageSum = number ;
                    tv_sign.setVisibility(messageSum > 0 ? View.VISIBLE : View.GONE);
                }
            });
        }
    };


    private View.OnClickListener onLoginOut = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            IFroChatMouleImpl.getInstance().updateAccount();
            Intent intent = new Intent(getActivity(),LoginActivity.class);
            startActivity(intent);
           finish();
        }
    };

    @Override
    protected void onDestroy() {
        super.onDestroy();
        FragmentUtils.clearFragment();
    }




    private UserPresenter presenter;

    private void nearByUsers(){
        Map<String,Object> map = new HashMap<>();
//            map.put("longitude",121.4179104567);
//            map.put("latitude",31.176031387);
        presenter.getNearByList(map);
    }

    @Override
    public void getData(final List<UserBean> list) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                adapter.addAll(list);
            }
        });
    }


    //#######################################demo#############################################
    private int cardWidth;
    private int cardHeight;

    private SwipeFlingAdapterView swipeView;
    private InnerAdapter adapter;
    @Override
    public void onItemClicked(MotionEvent event, View v, Object dataObject) {

    }

    @Override
    public void removeFirstObjectInAdapter() {
        adapter.remove(0);
    }

    @Override
    public void onLeftCardExit(Object dataObject) {

    }

    @Override
    public void onRightCardExit(Object dataObject) {

    }

    @Override
    public void onAdapterAboutToEmpty(int itemsInAdapter) {
        if (itemsInAdapter == 10) {
            loadData();
        }
    }

    @Override
    public void onScroll(float progress, float scrollXProgress) {

    }


    private void initView() {
        DisplayMetrics dm = getResources().getDisplayMetrics();
        float density = dm.density;
        cardWidth = (int) (dm.widthPixels - (2 * 18 * density));
        cardHeight = (int) (dm.heightPixels - (338 * density));

        swipeView = findViewById(R.id.swipe_view);
        if (swipeView != null) {
            swipeView.setIsNeedSwipe(true);
            swipeView.setFlingListener(this);
            swipeView.setOnItemClickListener(this);

            adapter = new InnerAdapter();
            swipeView.setAdapter(adapter);
        }

        View v = findViewById(R.id.swipeLeft);
        if (v != null) {
            v.setOnClickListener(onClickListener);
        }
        v = findViewById(R.id.swipeRight);
        if (v != null) {
            v.setOnClickListener(onClickListener);
        }

    }

    private View.OnClickListener onClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.swipeLeft:
                    swipeView.swipeLeft();
                    //swipeView.swipeLeft(250);
                    break;
                case R.id.swipeRight:
                    swipeView.swipeRight();
                    //swipeView.swipeRight(250);
            }
        }
    };


    private void loadData() {
        nearByUsers();
    }
    Random ran = new Random();

    private class InnerAdapter extends BaseAdapter {

        ArrayList<UserBean> objs;

        public InnerAdapter() {
            objs = new ArrayList<>();
        }

        public void addAll(Collection<UserBean> collection) {
            if (isEmpty()) {
                objs.addAll(collection);
                notifyDataSetChanged();
            } else {
                objs.addAll(collection);
            }
        }

        public void clear() {
            objs.clear();
            notifyDataSetChanged();
        }

        public boolean isEmpty() {
            return objs.isEmpty();
        }

        public void remove(int index) {
            if (index > -1 && index < objs.size()) {
                objs.remove(index);
                notifyDataSetChanged();
            }
        }

        @Override
        public int getCount() {
            return objs.size();
        }

        @Override
        public UserBean getItem(int position) {
            if(objs==null ||objs.size()==0) return null;
            return objs.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        // TODO: getView
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder holder;
            UserBean userBean = getItem(position);
            if (convertView == null) {
                convertView = LayoutInflater.from(parent.getContext()).inflate(R.layout.card_new_item, parent, false);
                holder  = new ViewHolder();
                convertView.setTag(holder);
                convertView.getLayoutParams().width = cardWidth;
                holder.portraitView = (ImageView) convertView.findViewById(R.id.portrait);
                //holder.portraitView.getLayoutParams().width = cardWidth;
                holder.portraitView.getLayoutParams().height = cardHeight;
                holder.nameView = (TextView) convertView.findViewById(R.id.name);
                //parentView.getLayoutParams().width = cardWidth;
                //holder.jobView = (TextView) convertView.findViewById(R.id.job);
                //holder.companyView = (TextView) convertView.findViewById(R.id.company);
                holder.cityView = (TextView) convertView.findViewById(R.id.city);
                holder.eduView = (TextView) convertView.findViewById(R.id.education);
                holder.workView = (TextView) convertView.findViewById(R.id.work_year);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }

            ImageLoader.getInstance().displayImage(userBean.getAvatar(),holder.portraitView);
            holder.nameView.setText(String.format("%s", userBean.getNickname()));
            //holder.jobView.setText(talent.jobName);

            final CharSequence no = "暂无";

            holder.cityView.setHint(no);
            holder.cityView.setText(userBean.getGender()+"");
            holder.cityView.setCompoundDrawablesWithIntrinsicBounds(0,R.drawable.home01_icon_location,0,0);

            holder.eduView.setHint(no);
            holder.eduView.setText(userBean.getId()+"");
            holder.eduView.setCompoundDrawablesWithIntrinsicBounds(0,R.drawable.home01_icon_edu,0,0);

            holder.workView.setHint(no);
            holder.workView.setText(userBean.getUpdateTime());
            holder.workView.setCompoundDrawablesWithIntrinsicBounds(0,R.drawable.home01_icon_work_year,0,0);

            return convertView;
        }

    }

    private static class ViewHolder {
        ImageView portraitView;
        TextView nameView;
        TextView cityView;
        TextView eduView;
        TextView workView;

    }

}


